package com.vcredit.creditcat.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vcredit.creditcat.enumtype.AuthItemEnum;
import com.vcredit.creditcat.manager.CreditCatProcessManager;
import com.vcredit.creditcat.model.AuthAlipay;
import com.vcredit.creditcat.model.AuthItem;
import com.vcredit.creditcat.model.AuthLog;
import com.vcredit.creditcat.persistence.AuthAlipayExtMapper;
import com.vcredit.creditcat.persistence.base.AuthAlipayMapper;

/**
 * 
 **/
@Service
public class AuthAlipayService {
	@Autowired
	private AuthAlipayMapper mapper;
	@Autowired
	private AuthAlipayExtMapper extMapper;
	@Autowired
	private CreditCatProcessManager creditCatProcessManager;
	@Autowired
	private AuthLogService authLogService;

	public void insert(AuthAlipay obj) {
		mapper.insert(obj);
	}

	public void update(AuthAlipay obj) {
		mapper.update(obj);
	}

	public List<AuthAlipay> findAll() {
		return mapper.findAll();
	}

	public List<AuthAlipay> find(AuthAlipay obj) {
		return mapper.find(obj);
	}

	public AuthAlipay findByProcessId(Long processId) {
		AuthAlipay authAlipay = new AuthAlipay();
		authAlipay.setProcessId(processId);
		List<AuthAlipay> list = find(authAlipay);
		if (!list.isEmpty())
			return list.get(0);
		return null;
	}

	public List<AuthAlipay> findUnCrawl() {
		return extMapper.findUnCrawl();
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void updateCreditAlipay(AuthAlipay param) throws Exception {
		AuthAlipay authAlipay = findByProcessId(param.getProcessId());
		if (authAlipay != null) {
			param.setAlipayProccessId(authAlipay.getAlipayProccessId());
			update(param);
		} else {
			insert(param);
		}
		if (null != param.getIsReal() && 1 == param.getIsReal()) {
			creditCatProcessManager.itemDone(new AuthItem(AuthItemEnum.ALIPAY.getCode()), param.getProcessId());
			authLogService.insert(new AuthLog(param.getProcessId(), param.getCust().getCustId(),
					AuthItemEnum.ALIPAY.getCode(), param.getExpiredTime(), new Date()));
		}
	}

	public void resetStatus(AuthAlipay param) {
		update(param);
	}
}